package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author houChen
 * @date 2021/12/18 14:52
 * @Description:
 */
@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone){
        //1、接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(StringUtils.isNotBlank(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis() -l < 60000 ){
                //60秒内不能再发送验证码
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
       // String code = UUID.randomUUID().toString().substring(0,5);
        String code = "5200";
        System.out.println("发送的验证码为：" + code);
        //验证码缓存到redis中，且过期时间为10分钟
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone, code + "_"+System.currentTimeMillis(),10, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone, code);
        return R.ok().put("data",code);
    }


    /**
     * RedirectAttributes : 模拟重定向携带数据，利用sesson原理，将数据放在sesson中，只要跳转到下一个页面取出数据后，
     *                      sesson中的数据就会删掉
     *
     * todo: 解决分布式下的sesson问题
     *
     */
    @PostMapping("/register")
    public String register(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes attributes){
        if(result.hasErrors()){
            Map<String,String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(fieldError -> {
                return fieldError.getField();
            }, fieldError -> {
                return fieldError.getDefaultMessage();
            }));
            attributes.addFlashAttribute("errors",errors);
            //校验出错，则转发到注册页面
            return "redirect:/reg.html";
        }

        //注册
        //1、校验验证码
        String code = vo.getCode();
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(StringUtils.isNotBlank(redisCode)){
            //校验验证码是否正确
            if(redisCode.split("_")[0].equals(code)){
                //校验通过后，删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //调用会员远程服务进行注册
                R r = memberFeignService.register(vo);
                if(r.getCode()==0){
                    //调用会员服务注册成功
                    //注册成功，回到登录页面
                    return "redirect:/login.html";

                }else{
                    //调用会员服务注册失败 ===》 注册失败
                    //重定向到注册页面 , 并提示注册错误信息
                    Map<String,String> errors = new HashMap<>();
                    errors.put("msg", r.getData(new TypeReference<String>(){}));
                    attributes.addFlashAttribute("errors",errors);
                    return "redirect:/reg.html";

                }
            }else{
                Map<String,String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                attributes.addFlashAttribute("errors",errors);
                return "redirect:/reg.html";
            }
        }else{
            //验证码过期了
            Map<String,String> errors = new HashMap<>();
            errors.put("code", "验证码已过期");
            attributes.addFlashAttribute("errors",errors);
            return "redirect:/reg.html";
        }
    }

    /**
     * @Description: 谷粒商城登录接口
     * @param vo
     * @author  houChen
     * @date  2021/12/25 21:44
     *
     * 因为参数是由form表单传递过来的，所以不能添加 @RequestBody注解，因为该注解只接收json形式的请求体
     */
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        R login = memberFeignService.login(vo);
        if(login.getCode()==0){
            MemberRespVo data = login.getData(new TypeReference<MemberRespVo>() {
            });
            session.setAttribute("loginUser", data);
            return "redirect:http://gulimall.com:10001/index.html";
        }else{
            Map<String,String> errors = new HashMap<>();
            errors.put("msg", (String)login.get("msg"));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:login.html";
        }
    }


    /**
     * @Description:  访问商城主页
     * @param null
     * @author  houChen
     * @date  2021/12/31 20:52
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute==null){
            return "login";
        }else{
            return "redirect:http://gulimall.com:10001/index.html";
        }
    }

}